<template>
    <Page name="找回密码">
      <div class="page-auth-content forget-pwd">
          <nav>
            <a :class="{'on':verify_type == type_enum.phone}" @click="changeRegisterType(type_enum.phone)">手机号码</a>
            <a :class="{'on':verify_type == type_enum.potato}" @click="changeRegisterType(type_enum.potato)">potato</a>
            <a :class="{'on':verify_type == type_enum.email}" @click="changeRegisterType(type_enum.email)">邮箱</a>
          </nav>
          <form class="auth-wrap" @keypress.enter="submit" onsubmit="return false">
            <div v-if='verify_type == type_enum.phone'>
              <div class="form-item fx fx-vc">
                <div class="form-label" @click="changeAreaCode">
                  <div class="fx fx-vc fx-between">
                    <span>+{{form[type_enum.phone].phone_area_code}}</span>
                    <i class="arrow"></i>
                  </div>
                </div>
                <Input type="tel" class="flex" v-model="form[type_enum.phone].phone" placeholder="请输入手机号码"/>
              </div>
              <div class="form-item fx fx-vc">
                <span class="form-label">验证码</span>
                <Input type="tel" class="flex" v-model="form[type_enum.phone].ver_code" placeholder="请输入验证码"/>
                <a @click="getVerCode($event)" class="ver-code" :disabled='!valid_ver(form[type_enum.phone].phone)'>{{ver_time_text(type_enum.phone)}}</a>
              </div>
              <div class="form-item fx fx-center">
                <span class="form-label">新密码</span>
                <Password class="flex" placeholder="6-30位含大小写字母数字组合" v-model="form[type_enum.phone].new_password" />
              </div>
            </div>
            <div v-else-if='verify_type == type_enum.potato'>
              <div class="form-item fx fx-vc">
                <div class="form-label" @click="changeAreaCode">
                  <div class="fx fx-vc fx-between">
                    <span>+{{form[type_enum.potato].potato_area_code}}</span>
                    <i class="arrow"></i>
                  </div>
                </div>
                <Input type="tel" class="flex" v-model="form[type_enum.potato].potato" placeholder="请输入手机号码"/>
              </div>
              <div class="form-item fx fx-vc">
                <span class="form-label">验证码</span>
                <Input type="tel" class="flex" v-model="form[type_enum.potato].ver_code" placeholder="请输入验证码"/>
                <a @click="getVerCode($event)" class="ver-code" :disabled='!valid_ver(form[type_enum.potato].potato)'>{{ver_time_text(type_enum.potato)}}</a>
              </div>
              <div class="form-item fx fx-center">
                <span class="form-label">新密码</span>
                <Password class="flex" placeholder="6-30位含大小写字母数字组合" v-model="form[type_enum.potato].new_password" />
              </div>
            </div>
            <div v-else>
              <div class="form-item fx fx-vc">
                <span class="form-label">邮箱</span>
                <Input type="email" class="flex" v-model="form[type_enum.email].email"  placeholder="请输入邮箱"/>
              </div>
              <div class="form-item fx fx-vc">
                <span class="form-label">验证码</span>
                <Input type="tel" class="flex" v-model="form[type_enum.email].ver_code" placeholder="请输入验证码"/>

                <a @click="getVerCode($event)" class="ver-code" :disabled='!valid_ver(form[type_enum.email].email)'>{{ver_time_text(type_enum.email)}}</a>
              </div>
              <div class="form-item fx fx-center">
                <span class="form-label">新密码</span>
                <Password class="flex" placeholder="6-30位含大小写字母数字组合" v-model="form[type_enum.email].new_password" />
              </div>
            </div>
            <a class="btn btn-block btn-primary submit" :disabled="!valid_form || posting" @click="submit($event)">{{posting ? '正在提交' : '提交'}}</a>
          </form>
          <span class="footer" @click="showContact">联系客服</span>
     </div>
     <ContactServiceModel />
  </Page>
</template>

<script>
import Page from '~/components/page';
import Password from '~/components/Password';
import Input from '~/components/Input';
import ContactServiceModel from '~/components/ContactServiceModel';

const type_enum =  {
  'phone': 1,
  'email': 2,
  'potato': 3,
}

export default {
  asyncData(context) {
    const { store,route } = context;
    let rs = {}
    if(route.params.country && route.params.data){
      let { form, verify_type } = route.params.data;
      let formType = form[verify_type];
      if(!!formType.phone){
        formType.phone_area_code = route.params.country.code;
      }else{
        formType.potato_area_code = route.params.country.code;
      }
      rs = {form,verify_type};
    }
    return rs;
  },
  components: {
    Page,
    Password,
    Input,
    ContactServiceModel
  },
  computed: {
    valid_ver(){
      return (value)=>!!String(value).trim() && !this.ver_type[this.verify_type].is_ver_valid;
    },
    valid_form(){
      let flag = true;

      //获取当前处理的表单
      let formType = this.form[this.verify_type];
      for(const i in formType){
        flag = flag && !!String(formType[i]).trim();
      }

      //是否已获取验证码
      if(!this.ver_type[this.verify_type].has_ver){
        flag = false;
      }
      return flag && !this.posting;
    },
    ver_time_text(){
      return (type)=>{
        return !this.ver_type[type].is_ver_valid ? ( this.ver_type[type].loading ? '加载中' : '获取验证码') : `${this.ver_type[type].ver_time}s后重试`;
      }
    }
  },
  data(){
    return {
      // 验证码类型
      ver_type: {
        [type_enum.phone]: {
          loading:false,
          ver_handel:false, // 定时器
          is_ver_valid: false, //验证码是否有效
          ver_time: 60, // 验证码重试倒计时
          has_ver:false, //是否已经获取验证码
        },
        [type_enum.potato]: {
          loading:false,
          ver_handel:false, // 定时器
          is_ver_valid: false, //验证码是否有效
          ver_time: 60, // 验证码重试倒计时
          has_ver:false, //是否已经获取验证码
        },
        [type_enum.email]: {
          loading:false,
          ver_handel:false, // 定时器
          is_ver_valid: false, //验证码是否有效
          ver_time: 60, // 验证码重试倒计时
          has_ver:false, //是否已经获取验证码
        },
      },
      form:{
        [type_enum.potato]:{
          potato_area_code:'354',
          potato:'',
          ver_code:'',
          new_password:''
        },
        [type_enum.phone]:{
          phone_area_code:'855',
          phone:'',
          ver_code:'',
          new_password:''
        },
        [type_enum.email]:{
          email:'',
          ver_code:'',
          new_password:''
        },
      },
      verify_type:1,
      posting:false,
      type_enum,
    }
  },
  mounted(){
  },
  methods: {
    changeAreaCode(){ // 修改手机区号
      // 缓存表单数据
      let {
          form,
          verify_type
        } = this.$data;


      this.$router.push({name:'area_list',
        query:{
          from:'forget_pwd'
        },
        params:{
          from:this.$route.name,
          data:{
            form,
            verify_type
          }
        }
      });
    },
    async getVerCode(e) { // 获取验证码
       let verType = this.ver_type[this.verify_type];
      if(e.currentTarget.getAttribute('disabled') || verType.is_ver_valid || verType.loading) return false;
      verType.loading = true;
      //获取验证码成功后input要获取焦点
      //这里不能反正ajax之后执行，浏览器处理机制问题
      try{
        let $input = e.target.parentNode.querySelector('input');
        $input && $input.focus();
      }catch(e){console.error(e)}

      //获取当前处理的表单
      let formType = this.form[this.verify_type];
      console.log(formType)
      let account;

      if(!!formType.email){
        account = formType.email
      }else if(!!formType.phone){
        account = `${formType.phone_area_code}${formType.phone}`
      }else {
        account = `${formType.potato_area_code}${formType.potato}`
      }
      console.log(account)
      let { data } = await this.$axios.post('?ct=member&ac=send_ver_code',{
        account,
        action:'forget_pwd',
        type:this.verify_type,
      });

      if(data.code == 0 ){
        verType.has_ver = true;
        verType.is_ver_valid = true;
        verType.ver_handel = setInterval(()=>{
          try {
            if(verType.ver_time == 0) {
              clearInterval(verType.ver_handel);
              verType.ver_handel = false;
              verType.ver_time = 60;
              verType.is_ver_valid = false;

            }
            verType.ver_time--;
          }catch(e){
            clearInterval(verType.ver_handel);
            verType.ver_handel = false;
            verType.is_ver_valid = false;
            this.$error(e);
          }

        },1000);

      }else{
        this.$toast(data.msg);
      }

      verType.loading = false;
    },
    changeRegisterType(verify_type) {// 修改注册类型
      this.verify_type = verify_type;
    },
    checkPassword(value){
      var lv = 0;var val = value;
      if (val.match(/[A-Z]/g)) {
        lv++;
      }
      if (val.match(/[a-z]/g)) {
        lv++;
      }
      if (val.match(/[0-9]/g)) {
        lv++;
      }

      if (lv < 3 || value.length < 6 || value.length >30) {
        this.$toast('密码格式不正确');
        return false;
      } else {
        return true;
      }
    },
    async submit(){
      if(this.posting || !this.valid_form ) return false;

      let formType = this.form[this.verify_type];
      if(!this.checkPassword(formType.new_password)) return false;

      try{
        // 检查用户是否已存在会员
        let { data:rs } = await this.$axios.post('?ct=member&ac=forget_pwd',{
          verify_type:this.verify_type,
          ...formType
        });

        if(rs.code == 0){
          this.$toast('修改密码成功',1000).then(()=>{
            this.$router.replace('/login');
          })
        }else{
          this.$toast(rs.msg);
        }
        this.posting = false;
      }catch(e){
        this.$error(e);
        this.posting = false;
      }
    },
    showContact(){
      this.$store.commit("wealth/SET_isShowContactServiceModel", true)
    }
  }
}
</script>

<style lang="less">
  @import url("~assets/less/module/auth.less");
  .forget-pwd {
    background-color:#fff;
    nav {
      display: flex;
      height:70px;
      border-bottom:1px solid #edeef0;

      a {
        position: relative;
        font-size:30px;
        width:50%;
        height:100%;
        display: flex;
        align-items: center;
        justify-content: center;

        &.on {
          color:#2086f9;
          &::after {
            content:'';
            position: absolute;
            left:0;
            right:0;
            bottom:4px;
            margin:auto;
            width:32px;
            height:4px;
            border-radius:4px;
            background-color:#2086f9;

          }
        }
      }
    }
  }
</style>
